package com.service;

import com.entity.BuildingInfo;
import com.repository.BuildingInfoRepository;
import com.repository.BuildingRentalRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.Optional;

@Service
public class BuildingInfoService {
    
    @Autowired
    private BuildingInfoRepository buildingInfoRepository;

    @Autowired
    private BuildingRentalRepository buildingRentalRepository;
    
    /**
     * 创建楼栋信息
     * @param buildingInfo 楼栋信息
     * @return 保存后的楼栋信息
     */
    public BuildingInfo create(BuildingInfo buildingInfo) {
        buildingInfo.setCreateTime(new Date());
        buildingInfo.setUpdateTime(new Date());
        return buildingInfoRepository.save(buildingInfo);
    }
    
    /**
     * 根据ID删除楼栋信息
     * @param id 楼栋ID
     */
    @Transactional
    public void deleteById(Integer id) {
        BuildingInfo buildingInfo = buildingInfoRepository.findById(id).get();
        buildingRentalRepository.deleteByBuildingCode(buildingInfo.getBuildingCode());
        buildingInfoRepository.deleteById(id);
    }
    
    /**
     * 更新楼栋信息
     * @param buildingInfo 楼栋信息
     * @return 更新后的楼栋信息
     */
    public BuildingInfo update(BuildingInfo buildingInfo) {
        buildingInfo.setUpdateTime(new Date());
        return buildingInfoRepository.save(buildingInfo);
    }
    
    /**
     * 分页查询楼栋信息
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 楼栋信息分页结果
     */
    public Page<BuildingInfo> findAll(int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        return buildingInfoRepository.findAll(pageable);
    }
    
    /**
     * 根据ID查询楼栋信息详情
     * @param id 楼栋ID
     * @return 楼栋信息
     */
    public BuildingInfo findById(Integer id) {
        Optional<BuildingInfo> buildingInfo = buildingInfoRepository.findById(id);
        return buildingInfo.orElse(null);
    }
}